const express = require('express');
const app = express();

const TAG = "[程序入口]";

const bodyParser = require('body-parser');

// 需要use的 application/json
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));

// 从命令行获取参数，以指定要加载的环境，如 node GB_gateway.js --profile tielu，要获取--profile tielu的参数值
const index = process.argv.indexOf('--profile');
let profile;
if (index < 0) {
    profile = "";
} else {
    profile = "_" + process.argv.slice(index + 1)[0];
}
console.info(TAG, '加载环境 profile=', profile);

// 动态加载配置文件
const configProfile = require(`./data/config${profile}`);
let config = require('./db/config');
config = Object.assign(config, configProfile);

// 引入日志组件
const log4js = require('./utils/logUtils');
const logger = log4js.getLogger('web');

// 设置express日志
log4js.useLogger(app, logger);

const networkUtils = require("./utils/networkUtils");
const deviceCache = require('./db/deviceCache');
const cacheUtils = require('./utils/cacheUtils');
const sipServer = require('./sip/server/server');
const dbManager = require('./db/dbmanager');
const freeLogsSchedule = require('./schedules/freeLogs');
const alertsCtrl = require('./service/alerts');
const adminCtrl = require('./controller/v1/admin');

// express 引入静态资源
app.use(express.static('public'));

// express 引入路由
const routers = require('./routers');
const register28181Schedule = require("./schedules/register28181");
const recorderSchedule = require("./schedules/recorder");
const proxyUtils = require("./service/proxyUtils");
for (const router in routers) {
    app.use(routers[router]);
}

process.on('SIGINT', () => {
    logger.info(TAG, '停止服务，保存临时文件，停止计划任务');
    freeLogsSchedule.stop();
    register28181Schedule.stop();
    recorderSchedule.stop();
    cacheUtils.save(async () => {
        dbManager.close();
        process.exit(0);
    });
});

/**
 * 启动 http 服务
 */
let server = app.listen(config.http.port, async function () {
    let host = server.address().address;
    let port = server.address().port;
    logger.info(TAG, `启动 Web 服务，请打开网址 : http://${host}:${port}`);

    // 恢复上次关闭前的设置
    await cacheUtils.load();
    await networkUtils.setConfigIp();
    /**从数据库加载配置 */
    dbManager.open();

    // 如果没有管理员信息则新建默认账号
    await adminCtrl.init();

    // 监控ftp文件夹，如果有数据则先处理
    if (alertsCtrl.init()) {
        // 监控文件夹，如果有新文件就处理
        alertsCtrl.inspect();
    }

    deviceCache.cameras = await proxyUtils.getAllPulls();
    sipServer.start();

    // 启用向上级连
    register28181Schedule.startSchedule();
    // 启动录像
    await recorderSchedule.startSchedule();
    // 启动定时清理日志
    freeLogsSchedule.start();
}).on('error', function (err) {
    logger.error(TAG, '启动 Web 服务失败', err);
    process.exit(0);
});
